package com.ruoyi.web.controller.personal;

import java.util.ArrayList;
import java.util.List;
import javax.mail.MessagingException;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.utils.email.EmailUtil;
import com.ruoyi.system.domain.EmailTemplates;
import com.ruoyi.system.service.IEmailTemplatesService;
import com.ruoyi.system.service.impl.EmailService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.SubscriberAccount;
import com.ruoyi.system.service.ISubscriberAccountService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;


/**
 * 通讯人员开户Controller
 *
 * @author ruoyi
 * @date 2025-01-07
 */
@RestController
@RequestMapping("/system/account")
public class SubscriberAccountController extends BaseController {
    @Autowired
    private ISubscriberAccountService subscriberAccountService;

    @Autowired
    private IEmailTemplatesService emailTemplatesService;

    /**
     * 查询通讯人员开户列表
     */
    @PreAuthorize("@ss.hasPermi('system:account:list')")
    @GetMapping("/list")
    public TableDataInfo list(SubscriberAccount subscriberAccount) {
        startPage();
        List<SubscriberAccount> list = subscriberAccountService.selectSubscriberAccountList(subscriberAccount);
        return getDataTable(list);
    }

    /**
     * 导出通讯人员开户列表
     */
    @PreAuthorize("@ss.hasPermi('system:account:export')")
    @Log(title = "通讯人员开户", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SubscriberAccount subscriberAccount) {
        List<SubscriberAccount> list = subscriberAccountService.selectSubscriberAccountList(subscriberAccount);
        ExcelUtil<SubscriberAccount> util = new ExcelUtil<SubscriberAccount>(SubscriberAccount.class);
        util.exportExcel(response, list, "通讯人员开户数据");
    }

    /**
     * 获取通讯人员开户详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:account:query')")
    @GetMapping(value = "/{accountId}")
    public AjaxResult getInfo(@PathVariable("accountId") Long accountId) {
        return success(subscriberAccountService.selectSubscriberAccountByAccountId(accountId));
    }

    @GetMapping("/gerateAcessnum")
    public AjaxResult generateAccessNumber() {
        List<String> accessNumbers = new ArrayList<>();

        while (accessNumbers.size() < 10) {
            // 生成9位随机数
            StringBuilder numberBuilder = new StringBuilder("13");
            for (int i = 0; i < 9; i++) {
                numberBuilder.append((int) (Math.random() * 10));
            }
            String accessNumber = numberBuilder.toString();

            // 检查号码是否已存在于数据库
            SubscriberAccount query = new SubscriberAccount();
            query.setPhoneNumber(accessNumber);
            List<SubscriberAccount> existingAccounts = subscriberAccountService.selectSubscriberAccountList(query);

            // 如果号码唯一且不在当前生成的列表中，则添加到结果集
            if (existingAccounts.isEmpty() && !accessNumbers.contains(accessNumber)) {
                accessNumbers.add(accessNumber);
            }
        }

        return success(accessNumbers);
    }

    /**
     * 新增通讯人员开户
     */
    @PreAuthorize("@ss.hasPermi('system:account:add')")
    @Log(title = "通讯人员开户", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SubscriberAccount subscriberAccount) throws MessagingException {
        EmailTemplates Template = emailTemplatesService.getEmailTemplateBySceneId("202501091507");
        String body = Template.getBody();
        String subject = Template.getSubject();
        String name = subscriberAccount.getName();
        String phoneNumber = subscriberAccount.getPhoneNumber();

        // 替换模板中的占位符
        body = body.replace("${username}", name);
        body = body.replace("${accessnum}", phoneNumber);

        logger.error("body:"+body);
        logger.error("subject:"+subject);
        EmailUtil.sendSimpleMail(subscriberAccount.getEmail(),subject,body);
        return toAjax(subscriberAccountService.insertSubscriberAccount(subscriberAccount));
    }

    /**
     * 修改通讯人员开户
     */
    @PreAuthorize("@ss.hasPermi('system:account:edit')")
    @Log(title = "通讯人员开户", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SubscriberAccount subscriberAccount) {
        return toAjax(subscriberAccountService.updateSubscriberAccount(subscriberAccount));
    }

    /**
     * 删除通讯人员开户
     */
    @PreAuthorize("@ss.hasPermi('system:account:remove')")
    @Log(title = "通讯人员开户", businessType = BusinessType.DELETE)
    @DeleteMapping("/{accountIds}")
    public AjaxResult remove(@PathVariable Long[] accountIds) {
        return toAjax(subscriberAccountService.deleteSubscriberAccountByAccountIds(accountIds));
    }
}
